package com.example.walled_houses.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.walled_houses.dto.UserDTO;
import com.example.walled_houses.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {

     private StringRedisTemplate stringRedisTemplate;

     public RefreshTokenInterceptor(StringRedisTemplate  stringRedisTemplate){
         this.stringRedisTemplate = stringRedisTemplate;
     }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO 获取请求头中的token
        String token = request.getHeader("Authorization");
        if(StrUtil.isBlank(token)){
            // TODO token直接放行
            return true;
        }
        // TODO 基于token获取redis中的用户信息
        String key = RedisConstants.LOGIN_USER_KEY + token;
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
        // TODO 判断用户是否存在
        if(entries.isEmpty()){
            // TODO 不存在放行
            return true;
        }
        // TODO 将查询到的Hash数据转为User对象
        User user = BeanUtil.fillBeanWithMap(entries, new User(), false);
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        // TODO 存在，保存用户信息到ThreadLocal中
        UserHolder.saveUser(userDTO);
        // TODO 刷新token有效期
        stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.DAYS);
        // TODO 放行
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
         //移除用户
        UserHolder.removeUser();
    }

}
